<template>
  <a-modal :width="830" v-model:visible="showImportPairDialog" :footer="false" title="导入SKU" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <a-spin style="width: 100%; height: 100%" :loading="loading" tip="sku导入中，请稍后...">
      <div class="step-w">
        <p class="title">第1步</p>
        <a-space>
          <span class="common-text">文件名：</span>
          <a-input v-model="fileName" placeholder="请输入文件名" />
          <span class="common-text ml10">导入模板：</span>
          <a-select @change="selTempalte" placeholder="请选择" v-model="templateId" style="width: 180px">
            <a-option v-for="(item, index) of templateList" :key="index" :value="item.id" :label="item.name"></a-option>
          </a-select>
          <a-button type="primary" @click="exportExcel">导出Excel表格</a-button>
          <a-dropdown>
            <a-button class="gray-outline">保存为模板 <icon-down /></a-button>
            <template #content>
              <a-doption @click.stop="uplateTemplate">覆盖当前模板</a-doption>
              <a-doption @click.stop="openCreateTempDialog">另存新模板</a-doption>
            </template>
          </a-dropdown>
        </a-space>

        <div class="sel-item-con mt10">
          <div class="top">
            <a-space>
              <div>所有字段</div>
              <div>
                <a-checkbox v-model="isSelAll">全选</a-checkbox>
              </div>
            </a-space>
          </div>
          <div class="bottom">
            <a-checkbox class="ml5 mb5" value="sku" disabled v-model="fixed">SKU</a-checkbox>
            <a-checkbox class="ml5 mb5" @change="checkCode" v-model="item.checked" v-for="(item, index) of propertyList" :key="index">{{ item.name }}</a-checkbox>
            <div class="sel-con">
              <div>Excel字段顺序</div>
              <div class="clearfix mt5" style="position: relative">
                <a-tag class="ml10 fl mb10 first-tag" color="arcoblue">SKU</a-tag>
                <div class="fl tag-con">
                  <a-tag :class="[index == 0 ? 'AAA' : '']" class="ml10 mb10 cursor" color="arcoblue" v-for="(item, index) of selList" :key="index">{{ item.name }}</a-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="step-w">
        <p class="title">第2步</p>
        <a-upload draggable action="/" accept=".xls,.xlsx" :limit="1" ref="uploadRef" :custom-request="uplaodFile">
          <template #upload-button>
            <div class="update-con">
              <i class="icon icon-shangchuan"></i>
              <p style="font-size: 16px">拖拽到此或点击上传表格</p>
              <p style="color: #999">（支持格式：xls、xlsx）</p>
            </div>
          </template>
        </a-upload>
      </div>
    </a-spin>

    <a-modal v-model:visible="showCreateTempDialog" width="400px" @ok="createTemplate" title="请输入模板名称" title-align="start" :mask-closable="false" @cancel="tempEditName = ''">
      <a-input v-model="tempEditName" />
    </a-modal>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, computed, nextTick } from 'vue'
  import { importProducts, getRelatedList, exportTemplate, saveOrUpdatePropImportTemplate, listPropImportTemplateByUserIds, importProductProp } from '@/api/product'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  import Sortable from 'sortablejs'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
  })

  let loading = ref(false)
  let showCreateTempDialog = ref(false)
  let fixed = ref(true)
  let selList: any = ref([])
  let fileName = ref('属性导入模板')
  let tempEditName = ref('')
  let templateId = ref('')
  let curTemInfo: any = ref({})
  let templateList: any = ref([])
  let propertyList: any = ref([])

  const showImportPairDialog = ref(props.isShow)
  const uploadRef = ref()

  // 关闭
  function closedDialog() {
    showImportPairDialog.value = false
    emit('closed')
  }
  // 开始上传
  const uplaodFile: any = async (option: any) => {
    let { fileItem, onProgress } = option
    let formData = new FormData()
    formData.append('file', fileItem.file)
    onProgress(0.5)
    loading.value = true
    let res: any = await importProductProp(formData)

    if (res) {
      onProgress(1)
      Message.success('导入成功')
      emit('success')
      closedDialog()
      loading.value = false
    } else {
      loading.value = false
      onProgress(0)
    }
  }

  const getPropertyList = async () => {
    const res: any = await getRelatedList({ pageSize: 99999999 })
    propertyList.value = res.data?.records || []
  }

  const isSelAll = computed({
    set(val) {
      propertyList.value.map((e: any) => (e.checked = val))
      setSelList()
    },
    get() {
      return propertyList.value.every((e: any) => e.checked)
    },
  })

  const setSelList = () => {
    selList.value = _.cloneDeep(propertyList.value.filter((e: any) => e.checked))
  }

  const rowDrop = () => {
    const body: any = document.querySelector('.tag-con')
    Sortable.create(body, {
      animation: 200, // 定义排序动画的时间
      forceFallback: true,
      filter: '.first-tag',
      onEnd(evt: any) {
        selList.value.splice(evt.newIndex, 0, selList.value.splice(evt.oldIndex, 1)[0])
        var newArray = selList.value.slice(0)
        selList.value = []
        nextTick(() => {
          selList.value = newArray
        })
      },
    })
  }

  const checkCode = () => {
    setSelList()
  }

  const exportExcel = async () => {
    if (!selList.value[0]) {
      return Message.error('请选择导出模板要显示的字段')
    }
    let params = {
      name: fileName.value,
      selectPropCodeList: selList.value.map((e: any) => e.code),
    }
    const res: any = await exportTemplate(params)
    if (res) {
      let a = document.createElement('a')
      a.target = '_blank'
      a.href = res.data.url
      a.click()
      a.remove()
    }
  }

  const openCreateTempDialog = () => {
    if (!selList.value[0]) {
      Message.error('请选择需要导出的字段')
      return
    }
    showCreateTempDialog.value = true
  }

  const createTemplate = async () => {
    if (!tempEditName.value) {
      Message.error('请输入模板名称！')
      return false
    }
    let params = {
      name: tempEditName.value,
      selectPropCodeList: selList.value.map((e: any) => e.code),
    }
    const res: any = await saveOrUpdatePropImportTemplate(params)
    if (res) {
      getTempalte()
      tempEditName.value = ''
      Message.success('模板新建成功')
    }
  }

  const getTempalte = async () => {
    const res: any = await listPropImportTemplateByUserIds({ userId: '1678678117656608770' })
    templateList.value = res.data || []
  }

  const selTempalte = (val: string) => {
    let item = templateList.value.find((item: any) => item.id === val)
    curTemInfo.value = item
    selList.value = []
    propertyList.value.map((e: any) => {
      e.checked = false
      return e
    })
    let arr = item.selectPropCodeList || []
    arr.forEach((e: any) => {
      let item = propertyList.value.find((item: any) => item.code === e)
      item.checked = true
      if (item) {
        selList.value.push(item)
      }
    })
  }

  const uplateTemplate = async () => {
    if (!curTemInfo.value.id) return Message.success('模板未选择')
    let params = {
      name: curTemInfo.value.name,
      id: curTemInfo.value.id,
      selectPropCodeList: selList.value.map((item: any) => item.code),
    }
    const res: any = await saveOrUpdatePropImportTemplate(params)
    if (res) {
      getTempalte()
      Message.success('模板编辑成功')
    }
  }

  onMounted(() => {
    getPropertyList()
    getTempalte()
    nextTick(() => {
      rowDrop()
    })
  })
</script>
<style lang="less" scoped>
  .tag-con {
    min-height: 30px;
    .AAA {
      margin-left: 60px !important;
    }
  }

  .sel-item-con {
    // margin: 0 10px;
    border: 1px dashed var(--color-border);
    border-radius: 5px;
    .top {
      height: 40px;
      line-height: 40px;
      padding-left: 10px;
      border-bottom: 1px solid #e3e3e3;
    }
    .bottom {
      padding: 10px;
      .sel-con {
        border: 1px dashed var(--color-border);
        padding: 10px;
        border-radius: 5px;
      }
    }

    .first-tag {
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .step-w {
    border: 1px dashed var(--color-border);
    border-radius: 4px;
    margin-bottom: 10px;
    padding: 10px;
    .title {
      margin-bottom: 10px;
    }
  }
  .info-text {
    color: #999;
    margin-top: 20px;
    font-size: 12px;
    .title {
      margin-bottom: 10px;
    }
  }
  .update-con {
    height: 160px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .icon {
      font-size: 36px;
      color: #999;
    }
  }
</style>
